# coding:utf-8


import requests
from TestCase.login import LoginCookie
from TestCase.dataPrepare import OBSYS
from Common.Config import Config

login = LoginCookie()
cookie = login.getSysCookie()
orderInfos = OBSYS().readOrderInfo()


class ReceivingLogistics():
    def __init__(self):
        self.cookie = cookie
        self.logisticsNum = orderInfos[0]
        env = Config().get_conf('comm', 'env')
        self.relayBoxNo = Config().get_conf(env, 'ob_relayBoxNo')
        self.orderNum = orderInfos[0]
        self.session = requests.session()

    # 发货
    def expressNum(self):
        url = 'http://uat.crm.aihuishou.com/order/editLogistics?IncludeOrderTrace=true&IncludeOrderOptions=true&IncludeOrderLogistics=true&_formatted=true'
        datas = {
            'orderNo': self.orderNum,
            'logisticsCompanyId': "1",
            'expressNo': self.logisticsNum
        }
        res = self.session.post(url, data=datas, cookies=self.cookie)
        print(res.text)
        error = res.json()['error']
        if error == 0:
            print("发货成功")
        else:
            print("发货失败")

    # ocs拆包，先设置运营中心
    def unpackage(self):
        set_operationalCentre_url = 'http://uat.ocs.aihuishou.com/OperationalCentre/Set'
        operationalCentre_data = {'centreId': 1}
        operationalCentre_result = self.session.post(set_operationalCentre_url, data=operationalCentre_data,
                                                     cookies=self.cookie)
        if operationalCentre_result.status_code == 200:
            print("设置运营中心成功")
        else:
            print("设置运营中心失败")

        unpackage_url = 'http://uat.ocs.aihuishou.com/logisticsexpress/unpackage'
        unpackage_datas = {'expressNo': self.logisticsNum}
        unpackage_result = self.session.post(unpackage_url, data=unpackage_datas, cookies=self.cookie)
        status = unpackage_result.json()['data']['status']
        if status == '拆包成功':
            print("运营中心拆快递成功" + unpackage_result.json()['data']['expressNo'])
        else:
            print("运营中心拆包失败")

    # ocs 收货
    def logistics(self):
        # 扫描物流单号地址
        ScanExpressNoUrl = 'http://uat.ocs.aihuishou.com/Reception/ScanExpressNo?expressNo=' + str(self.logisticsNum)
        ScanExpressNoData = {'expressNo': self.logisticsNum}

        # 获得待接收的物品地址
        SearchWaitReceiptProductUrl = 'http://uat.ocs.aihuishou.com/Reception/SearchWaitReceiptProduct'
        SearchWaitReceiptProductData = {'ExpressSerialNo': self.logisticsNum, 'ReceiveChannelNo': 100001}

        # 保存物流信息地址
        UpdateLogisticsReverse_url = 'http://uat.ocs.aihuishou.com/LogisticsReverse/Update'

        # 添加中转箱地址
        ScanAndBindRelayBox_url = 'http://uat.ocs.aihuishou.com/RelayBox/ScanAndBind'

        # 打标收货地址
        CheckInReceptionUrl = 'http://uat.ocs.aihuishou.com/Reception/CheckIn'

        # 移交中转箱地址
        TransferRelayBoxUrl = 'http://uat.ocs.aihuishou.com/RelayBox/Transfer'

        # 物流单号输入查找请求
        ScanExpressNoRequest = self.session.post(url=ScanExpressNoUrl, data=ScanExpressNoData, cookies=self.cookie)

        try:
            ScanExpressNoError = ScanExpressNoRequest.json()['error']
            if ScanExpressNoError == 0:
                logisticsSerialNo = ScanExpressNoRequest.json()['data']['logisticsSerialNo']

                SearchWaitReceiptProductRequest = self.session.post(url=SearchWaitReceiptProductUrl,
                                                                    data=SearchWaitReceiptProductData,
                                                                    cookies=self.cookie)
                SearchWaitReceiptProductError = SearchWaitReceiptProductRequest.json()['error']
                if SearchWaitReceiptProductError == 0:
                    productlevs = SearchWaitReceiptProductRequest.json()['data']
                    for i in range(len(productlevs)):
                        businessNos = dict(productlevs[i])
                        if businessNos['businessNo'] == self.orderNum:
                            agentNo = businessNos['agentNo']
                            channelNo = businessNos['channelNo']
                            receiveChannelNo = businessNos['receiveChannelNo']
                            mobile = businessNos['mobile']
                            productFlow = businessNos['productFlow']
                            productId = businessNos['productId']
                            productLevelId = businessNos['productLevelId']
                            id = businessNos['id']
                            skuId = businessNos['skuId']
                            skuName = businessNos['skuName']
                            amount = businessNos['linkedOrder']['amount']
                            # RelayBoxNo = getByOwner(productFlow)  # 根据流向添加中转箱

                            # 保存物流信息地址
                            UpdateLogisticsReverse_data = {'ArrivingCost': 0, 'ExtraCost': 0, 'IsPending': False,
                                                           'LogisticsCoopId': 1, 'LogisticsCoopName': '顺丰',
                                                           'LogisticsSerialNo': logisticsSerialNo, 'PaymentType': 1,
                                                           'SenderMobile': ''}
                            # 保存
                            UpdateLogisticsReverseRequest = self.session.post(url=UpdateLogisticsReverse_url,
                                                                              data=UpdateLogisticsReverse_data,
                                                                              cookies=self.cookie)
                            UpdateLogisticsReverseError = UpdateLogisticsReverseRequest.json()['error']

                            if UpdateLogisticsReverseError == 0:
                                SearchWaitReceiptProduc_datas = {'ExpressSerialNo': self.logisticsNum,
                                                                 'ReceiveChannelNo': receiveChannelNo,
                                                                 'Mobile': '', 'SearchAijihuiProduct': False}
                                SearchWaitReceiptProductRequests = self.session.post(url=SearchWaitReceiptProductUrl,
                                                                                     data=SearchWaitReceiptProduc_datas,
                                                                                     cookies=self.cookie)
                                SearchWaitReceiptProductErrors = SearchWaitReceiptProductRequests.json()['error']

                                if SearchWaitReceiptProductErrors == 0:

                                    # 添加中转箱
                                    ScanAndBindRelayBox_data = {
                                        'RelayBoxNo': self.relayBoxNo,
                                        'flow': productFlow
                                    }
                                    ScanAndBindRelayBoxRequest = self.session.post(url=ScanAndBindRelayBox_url,
                                                                                   data=ScanAndBindRelayBox_data,
                                                                                   cookies=self.cookie)
                                    ScanAndBindRelayBoxRequestError = ScanAndBindRelayBoxRequest.json()['error']
                                    if ScanAndBindRelayBoxRequestError == 0:
                                        # 添加物品
                                        checkInData = {'ExpressSerialNo': self.logisticsNum, 'IsChangeChannelNo': False,
                                                       'ProductNo': self.orderNum, 'RelayBoxNo': self.relayBoxNo,
                                                       'TurnOverContainerNo': '', 'WaitReceiptProductId': id}
                                        checkInRequest = self.session.post(url=CheckInReceptionUrl, data=checkInData,
                                                                           cookies=self.cookie)
                                        checkInError = checkInRequest.json()['error']
                                        if checkInError == 0:
                                            print('打标收货成功' + self.orderNum)
                                            # 移交中转箱
                                            TransferRelayBoxData = {'RelayBoxNo': self.relayBoxNo}
                                            TransferRelayRequest = self.session.post(url=TransferRelayBoxUrl,
                                                                                     data=TransferRelayBoxData,
                                                                                     cookies=self.cookie)
                                            TransferRelayRequestError = TransferRelayRequest.json()['error']
                                            if TransferRelayRequestError == 0:
                                                print('%s ' % TransferRelayRequest.json()['msg'])
                                            else:
                                                print('%s ' % TransferRelayRequest.json()['msg'])
                                        else:
                                            print('打标收货异常')
                                    else:
                                        print('检查是否存在等待处理的物品异常')
                                else:
                                    print('更新物流信息')
                            else:
                                print('快递单号没有对应的订单')
                        else:
                            print('快递单无该物品')
            else:
                print(ScanExpressNoRequest.json()['msg'])
        except:
            print('测试阻塞')

    # 质检接收
    def receiveProduct(self):
        # 获取箱子里的物品地址
        GetReceiveProductByRelayBoxNoUrl = 'http://uat.ocs.aihuishou.com/ProductReceiption/GetReceiveProductByRelayBoxNo?relayBoxNo=' + self.relayBoxNo + '&status=2'

        # 接收物品地址
        ReceiveProductProductReceiptionUrl = 'http://uat.ocs.aihuishou.com/ProductReceiption/ReceiveProduct'
        ReceiveProductProductReceiptionData = {}

        GetReceiveProductByRelayBoxNoRequest = self.session.get(url=GetReceiveProductByRelayBoxNoUrl,
                                                                cookies=self.cookie)
        GetReceiveProductByRelayBoxNoRequestError = GetReceiveProductByRelayBoxNoRequest.json()['error']

        if GetReceiveProductByRelayBoxNoRequestError == 0:
            productList = []
            for i in range(len(GetReceiveProductByRelayBoxNoRequest.json()['data']['validProductList'])):
                productList.append(
                    GetReceiveProductByRelayBoxNoRequest.json()['data']['validProductList'][i]['productNo'])
            for i in range(len(productList)):
                ReceiveProductProductReceiptionData.update({'TransferProductNos[%d]' % i: productList[i]})
            ReceiveProductProductReceiptionRequest = self.session.post(url=ReceiveProductProductReceiptionUrl,
                                                                       data=ReceiveProductProductReceiptionData,
                                                                       cookies=self.cookie)
            ReceiveProductProductReceiptionRequestError = ReceiveProductProductReceiptionRequest.json()['error']
            if ReceiveProductProductReceiptionRequestError == 0:
                print("接收物品成功：订单号" + str(ReceiveProductProductReceiptionRequest.json()['data']['successProduct']))
                # ReceiveProductProductReceiptionRequest.json()['data']['successProduct']的值为[{'productNo': '20180917181128160759'}]，是list
                return str(ReceiveProductProductReceiptionRequest.json()['data']['successProduct'])
            else:
                print("物品接收失败")

# if __name__ == '__main__':
#     R = ReceivingLogistics()
#     R.expressNum()
#     R.unpackage()
#     R.logistics()
#     R.receiveProduct()
